const jwt = require('jsonwebtoken');
const { Op } = require('sequelize');
const User = require('../models/User');
const { validateEmail, validatePassword, validateUsername } = require('../utils/validation');

const generateToken = (user) => {
  return jwt.sign({ id: user.id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN
  });
};

const register = async (req, res) => {
  try {
    const { email, password, username, walletAddress } = req.body;

    // Validate input
    if (!email || !password || !username) {
      return res.status(400).json({
        status: 'error',
        message: '邮箱、用户名和密码都是必填项'
      });
    }

    if (!validateEmail(email)) {
      return res.status(400).json({
        status: 'error',
        message: '请输入有效的邮箱地址'
      });
    }

    if (!validatePassword(password)) {
      return res.status(400).json({
        status: 'error',
        message: '密码至少需要6个字符'
      });
    }

    if (!validateUsername(username)) {
      return res.status(400).json({
        status: 'error',
        message: '用户名长度必须在3到20个字符之间'
      });
    }    // Check if user exists with email
    const existingUser = await User.findOne({
      where: {
        email
      }
    });

    if (existingUser) {
      return res.status(400).json({
        status: 'error',
        message: 'User with this email or wallet address already exists'
      });
    }

    const user = await User.create({
      email,
      password,
      username,
      walletAddress
    });

    const token = generateToken(user);

    res.status(201).json({
      status: 'success',
      user: {
        id: user.id,
        email: user.email,
        username: user.username
      },
      token
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const login = async (req, res) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) {
      return res.status(400).json({
        status: 'error',
        message: '邮箱和密码都是必填项'
      });
    }

    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(401).json({
        status: 'error',
        message: '用户不存在'
      });
    }

    if (!(await user.checkPassword(password))) {
      return res.status(401).json({
        status: 'error',
        message: '密码错误'
      });
    }

    const token = generateToken(user);

    res.json({
      status: 'success',
      user: {
        id: user.id,
        email: user.email,
        username: user.username
      },
      token
    });
  } catch (error) {
    res.status(401).json({
      status: 'error',
      message: '登录失败：' + error.message
    });
  }
};

const getProfile = async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      return res.status(404).json({
        status: 'error',
        message: '用户不存在'
      });
    }

    res.json({
      status: 'success',
      user: {
        id: user.id,
        email: user.email,
        username: user.username
      }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const updateProfile = async (req, res) => {
  try {
    const userId = req.user.id;
    const { username } = req.body;

    if (!validateUsername(username)) {
      return res.status(400).json({
        status: 'error',
        message: '用户名长度必须在1到10个字符之间'
      });
    }

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        status: 'error',
        message: '用户不存在'
      });
    }

    await user.update({ username });

    res.status(200).json({
      status: 'success',
      user: {
        id: user.id,
        email: user.email,
        username: user.username,
        exp: user.exp,
        level: user.level,
        nextLevelExp: user.nextLevelExp
      }
    });
  } catch (error) {
    console.error('Update profile error:', error);
    res.status(500).json({
      status: 'error',
      message: '更新用户信息失败'
    });
  }
};

const linkWallet = async (req, res) => {
  try {
    const { walletAddress } = req.body;
    const user = await User.findByPk(req.user.id);

    if (user.walletAddress) {
      throw new Error('Wallet already linked');
    }

    user.walletAddress = walletAddress;
    await user.save();

    res.json({
      status: 'success',
      data: {
        user: {
          id: user.id,
          email: user.email,
          username: user.username,
          walletAddress: user.walletAddress
        }
      }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

module.exports = {
  register,
  login,
  getProfile,
  updateProfile,
  linkWallet
};